/*
 * @lc app=leetcode.cn id=235 lang=typescript
 *
 * [235] 二叉搜索树的最近公共祖先
 */

// @lc code=start
/**
 * Definition for a binary tree node.
 * class TreeNode {
 *     val: number
 *     left: TreeNode | null
 *     right: TreeNode | null
 *     constructor(val?: number, left?: TreeNode | null, right?: TreeNode | null) {
 *         this.val = (val===undefined ? 0 : val)
 *         this.left = (left===undefined ? null : left)
 *         this.right = (right===undefined ? null : right)
 *     }
 * }
 */

function lowestCommonAncestor(root: TreeNode | null, p: TreeNode | null, q: TreeNode | null): TreeNode | null {
    const p_arr: any[] = [];
    const q_arr: any[] = [];
    loop(root, p, p_arr);
    loop(root, q, q_arr);
    // console.log(p_arr)
    // console.log(q_arr)
    for (let i = Math.min(p_arr.length, q_arr.length) - 1; i >= 0; i--) {
        // console.log(p_arr[i].val, q_arr[i].val)
        if (p_arr[i].val === q_arr[i].val) {
            return p_arr[i]
        }
    }
    return null
};

function loop(root: TreeNode | null, tar: TreeNode, arr: any) {
    if (!root) {
        return;
    }
    arr.push(root);
    if (root.val === tar.val) {
        return;
    }
    if (root.val > tar.val) {
        loop(root.left, tar, arr)
    } else {
        loop(root.right, tar, arr)
    }
}
// [6,2,8,0,4,7,9,null,null,3,5]\n2\n4
// @lc code=end

